﻿using LearningEnglish.LogicDSL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyX.DSL;
using System.Threading.Tasks;
using LearningEnglish.ViewModels;
using LearningEnglish.Models;
using LearningEnglish.ThridAPI;

namespace LearningEnglish.Controllers.Api
{
    public class WordBookController : Controller
    {

        [AcceptExAjax]
        [NormalJson]
        [CheckToken]
        public async Task<ActionResult> New(string name, string message, string img)
        {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(img))
                throw new Exception("关键值为空");

            var command = new CreateWordBook()
            {
                CreateUserID = this.GetRequestUser(),
                Name = name,
                Message = message,
                ImgID = Guid.Parse(img)
            };

            command.Send();

            var status = await command.Status();

            this.HandleStatus(status);

            return Json(new { id = command.Result().ToString() }, JsonRequestBehavior.AllowGet);
        }

        [AcceptExAjax]
        [NormalJson]
        [CheckToken]
        public ActionResult All()
        {
            var result = (from p in VM.WordBooks
                          where p.User.ID == this.GetRequestUser()
                          select new { id = p.ID, name = p.Name, message = p.Message, img = p.ImgPath }).ToList();
            return Json(new { wordbooks = result }, JsonRequestBehavior.AllowGet);
        }

        [AcceptExAjax]
        [CheckToken]
        [NormalJson]
        public async Task<ActionResult> Add(Guid id, string word)
        {
            var command = new AddWordIntoWordBook() { XSenderID = id, Word = word };
            command.Send();
            var status = await command.Status();
            this.HandleStatus(status);

            return Json(new { word = word, mean = command.Result().ToString() }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Test()
        {
            try
            {

                return Json(new { }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}